<!--
 * @Description: 自定义列组件
 * @Author: seadon
 * @LastEditors: seadon
 * @Date: 2021-04-11 11:31:08
 * @LastEditTime: 2022-04-22 17:18:50
-->
<template>
	<a-tooltip placement="top">
		<template #title>
			<div style="min-width: 70px">
				{{ $t('control.gridTable.columns.customHeader', '自定义表头') }}
			</div>
		</template>
		<a-popover
			placement="bottomLeft"
			trigger="click"
			v-model:visible="visible"
			class="rok-custom-columns"
		>
			<template #title>
				<a-button type="primary" size="small" @click.prevent="handleSave">{{
					$t('common.save', '保存')
				}}</a-button>
				<a-button size="small" style="margin-left: 12px" @click="handleReset">{{
					$t('common.reset', '重置')
				}}</a-button>
			</template>
			<template #content>
				<div class="popover-wrapper">
					<div :style="{ maxHeight: '220px' }">
						<a-checkbox-group
							v-model:value="checkedList"
							@change="handleChange"
							ref="columnRef"
						>
							<template v-for="item in columns" :key="item.dataIndex">
								<div>
									<a-checkbox :value="item.dataIndex">
										{{ item.title || item.customTitle }}
									</a-checkbox>
								</div>
							</template>
						</a-checkbox-group>
					</div>
				</div>
			</template>
			<a-button>
				<i class="low-code icon-customer_cell" />
			</a-button>
		</a-popover>
	</a-tooltip>
</template>

<script lang="ts">
import {
	defineComponent,
	PropType,
	onMounted,
	reactive,
	toRefs,
	unref,
	ref,
} from 'vue'
import { CheckedItem } from '../types/table'

export default defineComponent({
	name: 'custom-columns',
	props: {
		columns: {
			type: Array as PropType<Record<string, any>[]>,
			required: true,
			default: () => [],
		},
		checkList: {
			type: Array as PropType<string[]>,
			required: true,
			default: () => [],
		},
	},
	emits: ['onSetColumns'],
	setup(props, { emit }) {
		const checkState = reactive<CheckedItem>({
			checkedList: [],
			defaultCheckList: [],
		})
		const visible = ref<boolean>(false)

		function handleChange(checkedList: string[]) {
			checkState.checkedList = checkedList
		}

		function handleSave() {
			emit('onSetColumns', checkState.checkedList)
			visible.value = false
		}

		function handleReset() {
			checkState.checkedList = [...checkState.defaultCheckList]
			// handleSave()
		}

		onMounted(() => {
			checkState.defaultCheckList = unref(props.columns).map(
				item => item.dataIndex
			)

			checkState.checkedList = props.checkList
		})

		return {
			...toRefs(checkState),
			visible,
			handleChange,
			handleSave,
			handleReset,
		}
	},
})
</script>

<style lang="less" scoped>
.popover-wrapper {
	margin-right: -8px;
	width: 200px;
	overflow: auto;

	.ant-checkbox-group {
		display: block;

		.ant-checkbox-wrapper {
			display: block;
			text-overflow: ellipsis;
			white-space: nowrap;
			overflow: hidden;
		}
	}
}
.rok-custom-columns {
	padding: 0 8px;

	:deep svg {
		width: 16px !important;
		height: 16px !important;
	}
}
</style>
